import base64
import json
from xml.dom import minidom

import requests
from unipath import Path, FILES

api_key = 'e7b5d99923d0427492eb6233fca08e1c'
domain = 'http://localhost:8096/'
user_id = 'c24de12a959c4ce4b8adf7fa7f302ef9'


# 获取所有的库
# '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items'.format(domain)
# 库的信息明细
# '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/3227ce1e069754c594af25ea66d69fc7'.format(domain)
# 获取所有的电影
# '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/?SortBy=SortName&SortOrder=Ascending&IncludeItemTypes=Movie&Recursive=true'.format(domain)
# 获取指定库下的电影列表
# '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/?SortBy=SortName&SortOrder=Ascending&IncludeItemTypes=Movie&Recursive=true&ParentId=3227ce1e069754c594af25ea66d69fc7'.format(domain)
# 获取电影明细
# url = '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/{1}'.format(domain, actor_id)
# url = '{0}/emby/Items/13266/PlaybackInfo?UserId=adc41b08c4b1425a8dec3e90bdf611e7'.format(domain)
def get_movie_info(actor_id: int):
    url = '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/{1}'.format(domain, actor_id)
    headers = {
        'accept': 'application/json',
    }
    # 参数
    params = {
        'api_key': api_key
    }
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)

    # 查询失败
    if response.status_code != 200:
        return None

    return response.json()


# http://localhost:8096/emby/Items/107
# 更新员工信息
def update_movie_file_path(actor_id):
    movie_data = get_movie_info(actor_id)
    movie_data['MediaSources'][0]['Path'] = "F:\\艺术资源\\041916_282\\041916_282.mkv"
    movie_data['Path'] = "F:\\艺术资源\\041916_282\\041916_282.mkv"
    url = '{0}/emby/Items/{1}'.format(domain, actor_id)
    headers = {
        'Accept': '*/*',
        "Content-Type": "application/json;charset=UTF-8",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
    }
    # 参数
    params = {
        'api_key': api_key
    }
    # 请求数据
    response = requests.post(headers=headers, url=url, params=params, data=json.dumps(movie_data))

    # 查询失败
    return response.text


# 更新缺失的图片
def update_lib_image(lib_id: str):
    url = '{0}/emby/Users/{1}/Items/?SortBy=SortName&SortOrder=Ascending&IncludeItemTypes=Movie&Recursive=true&ParentId={2}'.format(domain, api_key, lib_id)
    headers = {'accept': 'application/json', }
    # 参数
    params = {'api_key': api_key}
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)
    if response.status_code != 200:
        return response.text
    for item in dict(response.json())['Items']:
        print("[!] ------------------------")

        movie_info = get_movie_detail(item['Id'])
        # 视频路径
        movie_path = Path(movie_info['Path'])
        print("[+] {0}".format(item['Name']))
        print("[+] {0}".format(movie_path))
        item_id = item['Id']
        server_id = item['ServerId']

        poster_path = None
        fanart_path = None
        thumb_path = None
        for item_pic_path in movie_path.parent.walk(filter=FILES):
            if not item_pic_path.ext.lower() in ['.jpg']:
                continue

            if item_pic_path.stem.split("-")[-1].lower() == 'poster':
                poster_path = item_pic_path
                continue
            if item_pic_path.stem.split("-")[-1].lower() == 'fanart':
                fanart_path = item_pic_path
                continue
            if item_pic_path.stem.split("-")[-1].lower() == 'thumb':
                thumb_path = item_pic_path
                continue

        if poster_path and (not ('Primary' in movie_info['ImageTags'].keys())):
            update_movie_pri_thu(item_id, poster_path, 'Primary')
            print('[+] - Primary {0}'.format(poster_path))

        if thumb_path and (not ('Thumb' in movie_info['ImageTags'].keys())):
            update_movie_pri_thu(item_id, thumb_path, 'Thumb')
            print('[+] - Thumb {0}'.format(thumb_path))

        if fanart_path and (len(movie_info['BackdropImageTags'])) == 0:
            update_movie_back_pic(item_id, fanart_path, server_id)
            print('[+] - Back {0}'.format(fanart_path))


# 获取所有的库
def show_all_lib():
    url = '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items'.format(domain)
    headers = {'accept': 'application/json', }
    # 参数
    params = {'api_key': api_key}
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)
    for item in dict(response.json())['Items']:
        print("{0} -> {1}".format(item['Name'], item['Id']))


# 统一nfo文件命名
def edit_nfo_name(lib_path: str):
    lib_path = Path(lib_path)
    if not lib_path.exists():
        print("[!] 不存在的路径")
        return
    # 有效的数据
    nfo_list = []
    [nfo_list.append(item_path) for item_path in lib_path.walk(filter=FILES) if item_path.ext.lower() in ['.nfo']]

    for item_path in nfo_list:
        targer_nfo_path = Path(item_path.parent, "movie.nfo")
        if targer_nfo_path.exists():
            print("[!]--->{0}".format(item_path))
            continue
        Path(item_path).rename(targer_nfo_path)
        print("[+] {0}".format(item_path))


# 获取电影媒体明细
def get_movie_detail(item_id: int):
    url = '{0}/emby/Users/{1}/Items/{2}'.format(domain, user_id, item_id)
    headers = {'accept': 'application/json', }
    # 参数
    params = {'api_key': api_key}
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)
    return dict(response.json())


# ********************************** 更新图片

# 更新 FAX-144-fanart
def update_movie_pri_thu(item_id: int, image_path: str, pic_type: str):
    # 地址
    url = '{0}/emby/Items/{1}/Images/{2}'.format(domain, str(item_id), pic_type)
    # 参数
    params = {'api_key': api_key}
    # 请求头信息
    headers = {'Content-Type': 'image/jpeg'}
    # 上传文件，返回结果
    response = requests.post(headers=headers, url=url, data=get_base64_str(image_path), params=params)
    return response.text


# 更新背景
def update_movie_back_pic(item_id: int, image_path: str, server_id: str):
    # 地址
    url = '{0}/emby/Items/{1}/Images/Backdrop/0?tag={2}'.format(domain, str(item_id), server_id)
    # 参数
    params = {'api_key': api_key}
    # 请求头信息
    headers = {'Content-Type': 'image/jpeg'}
    # 上传文件，返回结果
    response = requests.post(headers=headers, url=url, data=get_base64_str(image_path), params=params)
    return response.text


# 获取文件的base64编码字符串
def get_base64_str(file_path):
    """
        获取文件的base64编码字符串
    :param file_path: 文件路径
    :return: base64编码
    """
    return base64.b64encode(open(file_path, 'rb').read())


# ********************************** 工具
# 根据Nfo重命名文件
def rename_dir(dir_path):
    dir_path = Path(dir_path)
    if not dir_path.exists():
        print("[!] 文件夹不存在")
        return
    dir_list = dir_path.listdir()
    count = 0
    count_all = str(len(dir_list))
    print('[+]找到 {0} 文件夹'.format(count_all))

    # 已经存在dir
    exist_dir_list = []
    for item_movie_dir_path in dir_list:
        count = count + 1
        print("[*] ------------------- {0} [{1}/{2}] -------------- {3}".format((str(count / int(count_all) * 100)[:4] + '%'), str(count), str(count_all), item_movie_dir_path.stem))
        nfo_file_path = Path(item_movie_dir_path, "movie.nfo")
        if not nfo_file_path.exists():
            print("[!] nfo 不存在 ")

        new_dir_name = ''
        try:
            with open(nfo_file_path, 'r', encoding='utf8') as fh:
                # parse()获取DOM对象
                dom = minidom.parse(fh)
                # 获取根节点
                root = dom.documentElement
                # 通过dom对象或根元素，再根据标签名获取元素节点，是个列表
                movie_title = root.getElementsByTagName('title')[0].childNodes[0].data
                movie_year = root.getElementsByTagName('year')[0].childNodes[0].data
                # 获取节点属性
                new_dir_name = Path(item_movie_dir_path.parent, "{0}({1})".format(movie_title, movie_year))
        except Exception as ex:
            print("[!] 解析nfo文件异常")
        if len(new_dir_name) == 0:
            print('[$] 获取文件名失败')
            continue

        print("[+] 新目录 {0}".format(new_dir_name))
        if new_dir_name.exists():
            print("[!] 新目录已存在")
            if new_dir_name.stem in exist_dir_list:
                item_movie_dir_path.rename(Path(item_movie_dir_path.parent, "00-" + item_movie_dir_path.stem))
            else:
                exist_dir_list.append(new_dir_name.stem)
            continue
        item_movie_dir_path.rename(new_dir_name)

    print("[*]============================处理完成==========================")


# 删除重复的文件夹
def delete_dup_dir(dir_path):
    dir_path = Path(dir_path)
    if not dir_path.exists():
        print("[!] 文件夹不存在")
        return
    dir_list = dir_path.listdir()
    count = 0
    count_all = str(len(dir_list))
    print('[+]找到 {0} 文件夹'.format(count_all))
    exit_list = []
    will_delete_dir = []
    for item_movie_dir_path in dir_list:
        count = count + 1
        print("[*] ------------------- {0} [{1}/{2}] -------------- {3}".format((str(count / int(count_all) * 100)[:4] + '%'), str(count), str(count_all), item_movie_dir_path.stem))
        if item_movie_dir_path.stem in exit_list:
            will_delete_dir.append(item_movie_dir_path.stem)
            continue
        exit_list.append(item_movie_dir_path.stem)

    for item in will_delete_dir:
        print(item)
    print("[*]============================处理完成==========================")


# 检查视频文件及是否符合标准
def check_movie_info(dir_path):
    file_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm']
    dir_path = Path(dir_path)
    dirs = dir_path.listdir()
    count = 0
    count_all = str(len(dirs))
    print('[+]找到 {0} 文件夹'.format(count_all))
    error_list = []
    will_delete_list = []
    for dir_name in dirs:
        count = count + 1
        percentage = str(count / int(count_all) * 100)[:4] + '%'
        print('[!] ------------- ' + percentage + ' [' + str(count) + '/' + count_all + '] ------------- ' + dir_name)
        # 文件夹路径
        nfo_file_list = []
        jpg_file_list = []
        movie_file_list = []

        for item_file_name in dir_name.walk(filter=FILES):
            # nfo文件
            if item_file_name == 'movie.nfo':
                nfo_file_list.append(item_file_name)
                continue
            # 图片文件
            if item_file_name == 'fanart.jpg' or item_file_name == 'poster.jpg' or item_file_name == 'thumb.jpg':
                jpg_file_list.append(item_file_name)
                continue
            # 视频文件
            if Path(item_file_name).ext.lower() in file_type:
                movie_file_list.append(item_file_name)
                continue

            will_delete_list.append(item_file_name)
        try:
            if len(nfo_file_list) == 0 or len(jpg_file_list) == 0 or len(movie_file_list) == 0:
                error_list.append(dir_name)
        except:
            print("  [-] 操作异常")

    print("[*] *****************************************")
    print("[*] **************** 要删除")
    print("[*] *****************************************")
    for item in will_delete_list:
        # item.remove()
        print("[!] 删除 -> {0}".format(item))

    print("[*] *****************************************")
    print("[*] **************** 异常文件夹")
    print("[*] *****************************************")
    for item in error_list:
        print("[#] -> {0}".format(item))
    print("[*]============================处理完成==========================")


if __name__ == '__main__':
    # ssssss = update_movie_file_path(13254)
    show_all_lib()
    # update_lib_image('3372')
    # edit_nfo_name(r'E:\meta-data\动漫电影')
    # print(get_movie_detail(42820)['Path'])
    # rename_dir(r'E:\meta-data\影视合集\CMCT-1080P')
    # check_movie_info(r'E:\meta-data\影视合集\正常合集')
